package com.globalblue;

import java.util.Timer;
import java.util.TimerTask;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.globalblue.services.ServiceFileDownloader;

public class CronJob {
	private final Timer timer = new Timer();
	private int minutes = 15;
	public static final Logger logger = Logger.getLogger(CronJob.class);

	/**
	 * Web Call method.
	 * 
	 */
	public void getJobInfo() {
		try {
			// Properties from web.xml enviornment file
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			String ctxminutes = (String) envCtx.lookup("Minutes");
			this.minutes = Integer.parseInt(ctxminutes);
			startScheduler();
		} catch (Exception e) {
			logger.log(Level.ERROR, e);
		}
	}

	/**
	 * Method to start scheduler
	 */
	private void startScheduler() {
		try {
			timer.schedule(new TimerTask() {
				public void run() {
					try {
						scheduleParse();
					} catch (Exception e) {
						logger.log(Level.ERROR, e);
					}
				}

				private void scheduleParse() throws Exception {
					logger.log(Level.INFO, "Starting cron job");
					ServiceFileDownloader serviceDownloader = new ServiceFileDownloader();
					serviceDownloader.downloadFiles(serviceDownloader.getUpdatedServerIpList());
					logger.log(Level.INFO, "Ending cron job");
				}
			}, 0, this.minutes * 60 * 1000);
		} catch (Exception e) {
			logger.log(Level.ERROR, e);
		}
	}
}
